package com.caits.lbs.framework.services.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.caits.lbs.framework.log.CommonLogFactory;

/**
 * <p>MinaAcceptorServer</p>
 * <p>mina实现的nio服务侦听类.与NioSocketAcceptor类似</p>
 *
 * @author		周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version		0.0.0
 * <table style="border:1px solid gray;">
 * <tr>
 * <th width="100px">版本号</th><th width="100px">动作</th><th width="100px">修改人</th><th width="100px">修改时间</th>
 * </tr>
 * <!-- 以 Table 方式书写修改历史 -->
 * <tr>
 * <td>0.0.0</td><td>创建类</td><td>zhouhuabin</td><td>2014年9月25日 下午3:20:46</td>
 * </tr>
 * <tr>
 * <td>XXX</td><td>XXX</td><td>XXX</td><td>XXX</td>
 * </tr>
 * </table>
*/
public class MinaAcceptorServer{

	/** TODO */
	private Logger log = CommonLogFactory.getLog();
	/** 侦听对象 */
	private NioSocketAcceptor nsa;
	/**
	 * 
	 * 启动数据监听服务
	 */

	public void startup() {

		try {
			nsa = new NioSocketAcceptor();
			DefaultIoFilterChainBuilder dfc = nsa.getFilterChain();
			/*
	         * 这里注意点:
	         * 1:TextLineCodecFactory设置这个过滤器一行一行(/r/n)的读取数据
	         * 2.ObjectSerializationCodecFactory一般接收的是对象等形象,以对象形式读取
	         */
			dfc.addLast("ObjectData", new ProtocolCodecFilter(new TextLineCodecFactory()));
			dfc.addLast("ThreadPool",new ExecutorFilter(Executors.newCachedThreadPool()));
			nsa.setReuseAddress(true);
			nsa.getSessionConfig().setBothIdleTime(30);
			nsa.setHandler( new ServerIoHandler());
			nsa.bind(new InetSocketAddress(8899));
			log.info("短信通道信息处理端服务监听器已开启......");

		} catch (IOException e) {
			log.error("启动侦听异常,msg="+e.getLocalizedMessage(),e);
		}
	}

	/**
	 * 
	 * 关闭数据监听服务
	 */

	public void shutdown() {

		nsa.dispose();

		System.out.println("短信通道信息处理端服务监听器已关闭......");

	}

	public static void main(String[] args) {
		new MinaAcceptorServer().startup();
	}
}